package com.flyme.module.base.provider.nuonuo.oauth;


import cn.hutool.json.JSONUtil;
import com.flyme.module.base.provider.nuonuo.utils.StateData;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * ISV类用户在获取到auth_code后可套用此方法
 *
 * @author sdk.jss.com.cn
 * @version 2.0
 * @since jdk1.6
 **/
public class Oauth2AccessToken {

    static String _url = StateData.accessToken_url; //获取token地址
    static String _header = StateData.contentType;  //http发送模式
    static String client_id = StateData.client_id;  //创建应用后，分配给应用的appKey
    static String client_secret = StateData.client_secret; //创建应用后，分配给应用的appSecret
    static String token_grant_type = StateData.grant_type_token;   //授权类型，在本步骤中，此值为“authorization_code”
    static String redirect_uri = StateData.redirect_uri;   //回调地址，必传且不能为空



    /**
     * 获取去token
     *
     * @return
     */
    public static String getAccessToken(String code, String taxNum) {
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try {
            client = HttpClients.createDefault();
            HttpUriRequest build = RequestBuilder
                    .post(_url)
                    .addHeader("Content-Type", _header)
                    .addParameter("client_id", client_id)
                    .addParameter("client_secret", client_secret)
                    .addParameter("grant_type", token_grant_type)
                    .addParameter("redirect_uri", redirect_uri)
                    .addParameter("code", code)
                    .addParameter("taxNum", taxNum)
                    .build();

            //请求
            response = client.execute(build);
            HttpEntity entity = response.getEntity();

            String resValue = "";
            if (entity != null) {
                resValue = EntityUtils.toString(entity);
                System.out.println("response: " + resValue);
            }
            //释放资源
            EntityUtils.consume(entity);
            return resValue;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                client.close();
                response.close();
            } catch (IOException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
        }
        return null;
    }

    public static void main(String[] args) {
        String resValue="{aa:'11',bb:{dd:'33'}}";
       String a= JSONUtil.toXmlStr(JSONUtil.parse(resValue));
        System.out.println(a);

    }


}
